package com.jollychic.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xusheng
 */
@RestControllerAdvice //aop切面
public class GlobalException {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String, Object> globalException(Exception e, HttpServletRequest request){
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("realMsg",e.getMessage());
        map.put("url",request.getRequestURL());

        if (e instanceof JollyExecption){
            JollyExecption jollyExecption= (JollyExecption) e;
            map = getJollyException(map,jollyExecption);
        }
        else {
            map = getException(map);
        }
        return map;
    }

    /**
     * 自定义异常
     * @param jollyExecption
     * @return
     */
    private Map<String,Object> getJollyException(Map<String, Object> map,
                                                 JollyExecption jollyExecption){
        map.put("code",jollyExecption.getCode());
        map.put("msg",jollyExecption.getMsg());
        return map;
    }

    /**
     * 系统异常
     * @return
     */
    private Map<String,Object> getException(Map<String, Object> map){
        map.put("code","1001");
        map.put("msg","系统错误");
        return map;
    }


}


